<?php

namespace Operation\Controller;

use Think\Controller;
use Think\IFilter;
use Think\IReq;
use Think\ISafe;
use Think\IClient;
use Think\ITime;
use Think\Util;
use Think\Plugin;
use Think\Verify;

/*
 * 后台登录
 */

class LoginController extends Controller {

    public $layout = '';

    //后台登陆
    function index() {
        $this->display();
    }

    function login_act() {
        $admin_name = IFilter::act(IReq::get('admin_name'));
        $password = IReq::get('password');
        $captcha = IReq::get('captcha', 'post');
        $_captcha = new \Think\Verify();

        $message = '';

        if ($admin_name == '') {
            $message = '登录名不能为空';
        } else if ($password == '') {
            $message = '密码不能为空';
        } else if (!$captcha || !$_captcha->check($captcha)) {
            $message = '验证码输入不正确';
        } else {
            $adminRow = M('admin')->where(array('admin_name' => $admin_name))->find();
            if (!empty($adminRow) && ($adminRow['password'] == md5($password)) && ($adminRow['is_del'] == 0)) {
                $dataArray = array(
                    'id' => $adminRow["id"],
                    'last_ip' => IClient::getIp(),
                    'last_time' => ITime::getDateTime(),
                );
                M('admin')->save($dataArray);

                //根据角色分配权限
                if ($adminRow['role_id'] == 0) {
                    ISafe::set('admin_role_name', '超级管理员');
                } else {
                    $roleObj = M('admin_role');
                    $where = array(
                        'id' => $adminRow["role_id"],
                        'is_del' => 0
                    );
                    $roleRow = $roleObj->where($where)->find();
                    //dump($roleRow);die;
                    ISafe::set('admin_role_name', $roleRow['name']);
                }
                ISafe::set('admin_id', $adminRow['id']);
                ISafe::set('admin_name', $adminRow['admin_name']);
                ISafe::set('admin_pwd', $adminRow['password']);
                
                $this->redirect("Operation/Index/index");
            } else {
                $message = '用户名与密码不匹配';
            }
        }

        if ($message != '') {
            $this->admin_name = $admin_name;
            $this->redirect('index', false);
            Util::showMessage($message);
        }
    }

    //后台登出
    function logout() {
        Plugin::trigger('clearAdmin');
        $this->redirect('index');
    }

    //加载验证码
    public function verify() {
        ob_clean();
        $Verify = new Verify();
        $Verify->fontSize = 20;
        $Verify->length = 4;
        $Verify->useNoise = false;
        $Verify->entry();
    }

}
